<?php
namespace app\lnadmin\controller;

use app\common\controller\AdminBase;
use app\common\model\User;
use app\common\model\Taocan;
use app\common\model\StoreGroup;
use app\common\model\StoreRule;
use app\common\model\StoreAuth;
use app\common\model\Store as Model;

class Store extends AdminBase
{
    public function initialize()
    {
        parent::initialize();
        $this->taocan = Taocan::get_list();
    }

    /**
     * 商户列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch('index');
    }
    public function index_json($limit='15')
    {
        $list = Model::with(['taocan'])->withCount(['log'])->order('id desc')->paginate($limit);
        $this->result($list);
    }

    /**
     * 新增商户
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $verify = input('_verify', true);
            try{
                $this->validate($param, 'store');
            }catch (\Exception $e){
                $this->error($e->getMessage());
            }
            empty($param['password']) && $this->error('密码不能为空');
            $result = Model::create($param);
            if ($result == true) {
                //添加部门
                $authgroup['store_id'] = $result->id;
                $authgroup['name'] = "总经理";
                $authgroup['status'] = "1";
                $aug = StoreGroup::create($authgroup);
                //获取所有权限列表
                $authgroup['rules'] = Taocan::where('id',$param['taocan'])->value('rules');
                $rule = StoreRule::create($authgroup);
                //添加总管理员
                $adduser['store_id'] = $authgroup['store_id'];
                $adduser['name'] = $param['contact'];
                $adduser['mobile'] = $param['mobile'];
                $adduser['password'] = $param['password'];
                $adduser['status'] = "1";
                $adduser['group_id'] = $aug->id;
                $adduser['rule_id'] = $rule->id;
                $user = User::create($adduser);
                //更新管理员
                Model::where('id',$result->id)->update(['admin_id'=>$user->id]);
                $this->success('操作成功', url('lnadmin/store/index'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('add',['taocan'=> $this->taocan]);
    }

    /**
     * 编辑商户
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $id = input('id') ?: '参数错误';
        $data = Model::where('id',$id)->find();
        if ($this->request->isPost()) {
            $param = $this->request->param();
//            //验证规则
            $verify = input('_verify', true);
            if($verify!='0'){
                try{
                    $this->validate($param, 'shop_edit');
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
            }
            $resule = Model::update($param,['id'=>$param['id']]);
            if ($resule == true) {
                cache('shop_domain',null);
                cache('shop_info'.$param['id'],null);
                insert_admin_log('修改了商家');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save',[
            'data' => $data,
            'taocan'=> $this->taocan
        ]);
    }

    /**
     * 删除商户
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Model::destroy($param['id']);
            insert_admin_log('删除了商家');
            $this->success('删除成功');
        }
    }

    /**
     * 套餐列表
     * @return mixed
     */
    public function taocan()
    {
        return $this->fetch('taocan');
    }
    public function taocan_json($limit)
    {
        $list = Taocan::order('id desc')->paginate($limit);
        $this->result($list);
    }

    /**
     * 添加套餐
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add_taocan()
    {
        if ($this->request->isPost()) {
            $result = Taocan::create($this->request->param());
            if ($result == true) {
                insert_admin_log('添加了套餐');
                $this->success('添加成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $userAuthRule = collection(StoreAuth::where(['status' => 1])->order('sort_order asc')->select())->toArray();
        foreach ($userAuthRule as $k => $v) {
            //$authRule[$k]['open'] = true;
        }
        return $this->fetch('save_taocan', ['userAuthRule' => list_to_tree($userAuthRule)]);
    }

    /**
     * 编辑套餐
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit_taocan()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            //更新数据
            $resule = Taocan::update($param,['id'=>$param['id']]);
            if ( $resule == true) {
                insert_admin_log('修改了套餐');
                $this->success('修改成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        $data     = Taocan::where('id', input('id'))->find();
        $userAuthRule = collection(StoreAuth::where(['status' => 1])->order('sort_order asc')->select())->toArray();
        foreach ($userAuthRule as $k => $v) {
            // $authRule[$k]['open'] = true;
            $userAuthRule[$k]['checked'] = in_array($v['id'], explode(',', $data['rules']));
        }
        return $this->fetch('save_taocan', ['data' => $data, 'userAuthRule' => list_to_tree($userAuthRule)]);
    }

    /**
     * 删除套餐
     */
    public function del_taocan()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            Taocan::destroy($param['id']);
            insert_admin_log('删除了套餐');
            $this->success('删除成功');
        }
    }
    /**
     * 成员列表
     * @return mixed
     */
    public function user()
    {
        return $this->fetch('user');
    }
    public function user_json($limit='15')
    {
        $list = User::with('group')->order('id desc')->paginate($limit);
        $this->result($list);
    }

    /**
     * 修改用户密码
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit_user($id)
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            empty($param['new_password']) && $this->error('请输入新密码');
            empty($param['rep_password']) && $this->error('请输入确认密码');
            $param['new_password'] != $param['rep_password'] && $this->error('两次密码不一致');
            $data = ['password' => $param['new_password']];
            $result = User::update($data,['id'=> $id]);
            if ($result == true) {
                $this->success('更新成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save_user');
    }
    
}
